<!DOCTYPE html>
<html lang="zh-cn">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>模态框</title>
    <style>
      .modal-wrap {
        position: fixed;
        inset: 0;
        z-index: 1000;
        background-color: rgba(5, 5, 5, 0.05);
      }
      .modal {
        width: 30%;
        height: 200px;
        background-color: #ffff;
        border-radius: 8px;
        margin: 10% auto;
        position: relative;
      }
      .modal .header {
        font-size: 1.5em;
        line-height: 32px;
        margin-top: 10px;
        margin-bottom: 10px;
        text-align: center;
        position: relative;
      }
      .modal .btn-close {
        position: absolute;
        right: 10px;
      }
      .modal .btn-close:hover {
        cursor: pointer;
      }
      .modal .body {
        padding: 0 20px 0 20px;
      }
      .modal .footer {
        position: absolute;
        right: 20px;
        bottom: 10px;
      }
    </style>
  </head>
  <body>
    <button id="btn-open">弹出模态框</button>
    <div class="modal-wrap" hidden>
      <div class="modal">
        <div class="header">
          模态框标题
          <span class="btn-close">X</span>
        </div>
        <div class="body">模态框内容</div>
        <div class="footer">
          <button>取消</button>
          <button>确认</button>
        </div>
      </div>
    </div>
    <script>
      const btn_open = document.getElementById("btn-open");
      const modal_wrap = document.querySelector(".modal-wrap");
      btn_open.onclick = () => {
        modal_wrap.hidden = false;
      };
      document.querySelector(".footer").onclick = document.querySelector(
        ".btn-close"
      ).onclick = () => {
        modal_wrap.hidden = true;
      };
      modal_wrap.addEventListener("click", (event) => {
        const modal = event.target.closest(".modal");
        if (!modal) modal_wrap.hidden = true;
      });
    </script>
  </body>
</html>
